package com.taxshare.purchaser.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageInfoRequest;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.constant.ResultConstant;
import com.taxshare.purchaser.entity.ElectronicledgerEntity;
import com.taxshare.purchaser.entity.InvoiceAuthProcessingEntity;
import com.taxshare.purchaser.entity.PeriodEntity;
import com.taxshare.purchaser.mapper.ElectronicledgerMapper;
import com.taxshare.purchaser.mapper.PeriodMapper;
import com.taxshare.purchaser.mapper.invoiceAuthsMapper;
import com.taxshare.purchaser.remote.ApiClientService;
import com.taxshare.purchaser.util.CodeConvertUtil;
import com.taxshare.purchaser.util.LqHttpUtil;
import com.taxshare.purchaser.view.dto.*;
import com.taxshare.purchaser.view.vo.AuthApplyContentRespVO;
import com.taxshare.purchaser.view.vo.AuthApplyInfoVO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @ClassName: InvoiceAuthService
 * @Description:
 * @author: luozhongyi
 * @date: 2021/4/12 14:46
 */
@Slf4j
@Service
@Transactional
public class InvoiceAuthService extends ServiceImpl<ElectronicledgerMapper, ElectronicledgerEntity> {

    @Autowired
    ApiClientService apiClientService;

    @Autowired
    PeriodMapper periodMapper;
    @Autowired
    invoiceAuthsMapper invoiceAuthsMapper;

    @Autowired
    AsyncAuthService asyncAuthService;

    @Autowired
    CommService commService;

    @Value("${lqpt.url}")
    private String url;
    /**
     * 前台异步发票认证
     *
     * @param
     * @return
     */
//    public Response invoiceAuth(InvoiceAuthModeDTO invoiceAuthModeDTO) {
//        //封装发票认证参数
//        List<InvoiceAuthItemDTO> parames = invoiceAuthModeDTO.getParames();
//        String anthMode = invoiceAuthModeDTO.getAuthMode();
//        InvoiceAuthBodyDTO authBody;
//        Map<String, InvoiceAuthBodyDTO> allMap = new HashMap<>();
//        Map<String, String> map;
//        List<Map<String, String>> invoices;
//        List<String> uuidList = new ArrayList();
//        List<String> authInvoices = new ArrayList();
//        //组装参数认证
//        for (InvoiceAuthItemDTO fpdmHm : parames) {
//            invoices = new ArrayList();
//            authBody = new InvoiceAuthBodyDTO();
//            map = new HashMap<>();
//            map.put("InvoiceCode", fpdmHm.getInvoiceCode());
//            map.put("InvoiceNumber", fpdmHm.getInvoiceNo());
//            map.put("ValidTax", fpdmHm.getValidTax());
//            if (allMap.size() > 0) {
//                if (null == allMap.get(fpdmHm.getPurchaserTaxno())) {
//                    invoices.add(map);
//                    authInvoices.add(fpdmHm.getInvoiceId());
//                    authBody.setNsrsbh(fpdmHm.getPurchaserTaxno());
//                    authBody.setFpList(invoices);
//                    authBody.setUuidList(authInvoices);
//                    //区分认证模式
//                    authBody.setAuthMode(anthMode);
//                    allMap.put(fpdmHm.getPurchaserTaxno(), authBody);
//                } else {
//                    InvoiceAuthBodyDTO exit = allMap.get(fpdmHm.getPurchaserTaxno());
//                    exit.getFpList().add(map);
//                    exit.getUuidList().add(fpdmHm.getInvoiceId());
//                }
//            } else {
//                invoices.add(map);
//                authInvoices.add(fpdmHm.getInvoiceId());
//                authBody.setFpList(invoices);
//                authBody.setNsrsbh(fpdmHm.getPurchaserTaxno());
//                authBody.setUuidList(authInvoices);
//                //区分认证模式
//                authBody.setAuthMode(anthMode);
//                allMap.put(fpdmHm.getPurchaserTaxno(), authBody);
//            }
//            uuidList.add(fpdmHm.getInvoiceId());
//        }
//        //根据发票ID和勾选标记，校验是否存在不可勾选的数据
//        QueryWrapper<ElectronicledgerEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("invoice_id", uuidList);
//        queryWrapper.eq("invoice_flag", CodeConstant.COMM_CODE_0);
//        if (baseMapper.selectCount(queryWrapper) > 0) {
//            return Response.error("PUR_ERROR_007");
//        }
//        //认证模式为勾选认证，将发票更新为待认证
//        if(CodeConstant.COMM_CODE_1.equals(anthMode)){
//            updateInvoiceWait(uuidList);
//        }
//        for (Map.Entry<String, InvoiceAuthBodyDTO> entry : allMap.entrySet()) {
//            asyncAuthService.auth(entry.getValue());
//        }
//        return Response.success();
//    }


    public Response invoiceAuth(Map<String, Object> map) {
        Map<String,Object> resultMap = new HashMap();
        String gfsbh = (String) map.get("gfsbh");
        String gxlxDm = (String) map.get("gxlxDm");
        List fpList = (List) map.get("fpmx");
        if (fpList.size() > 2000) {
            log.error("传入发票长度：", fpList.size());
            return Response.error("9999", "认证发票张数不能超过2000张！");
        }

        log.info("========批量上传抵扣发票 ========开始======");
        JSONObject reqJson = new JSONObject();
        reqJson.put("gfsbh",gfsbh);
        reqJson.put("gxlxDm",gxlxDm);
        reqJson.put("fpList",fpList);
        String reqStr = reqJson.toJSONString();
        try{
            url = url+"203065/PLFPDKGX";
            LqHttpUtil lqHttpUtil = new LqHttpUtil();
            JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
            String returncode = result_json.getString("returncode");
            if("00".equals(returncode)) {
                String returnmsg = result_json.getString("returnmsg");
                String pclsh = result_json.getString("pclsh");
//                String fpmx = result_json.getString("fpmx");
                InvoiceAuthProcessingEntity invoiceAuthProcessingEntity = new InvoiceAuthProcessingEntity();
//                invoiceAuthProcessingEntity.setFpmx(fpmx);
                invoiceAuthProcessingEntity.setNsrsbh(gfsbh);
                invoiceAuthProcessingEntity.setPclsh(pclsh);
                invoiceAuthProcessingEntity.setState("0");
                invoiceAuthProcessingEntity.setAuthState(gxlxDm);
                JSONArray fpmxArray = result_json.getJSONArray("fpmx");//明细数据(fpm
                if (fpmxArray!= null) {
                    for (Object obj : fpmxArray) {
                        JSONObject fpmxJson = (JSONObject) obj;
                        ElectronicledgerEntity electronicledgerEntity = new ElectronicledgerEntity();
                        String fphm = (String) fpmxJson.get("fphm");
                        //根据上传状态 更改发票认证状态  00：成功；01：失败
                        String sczt = (String) fpmxJson.get("sczt");
                        if (sczt.equals("00")){
                            electronicledgerEntity.setAuthState("4");//4-认证中
                        }else {
                            electronicledgerEntity.setAuthState("2");//2-认证失败
                            electronicledgerEntity.setAuthResult("99");//其他
                            electronicledgerEntity.setAuthResultContent((String) fpmxJson.get("errormsg"));//错误信息01：失败时记录失败原因
                        }
                        UpdateWrapper<ElectronicledgerEntity> updateWrapper = new UpdateWrapper();
                        updateWrapper.eq("invoiceNo",fphm);
                        baseMapper.update(electronicledgerEntity, updateWrapper);
                    }
                }
                invoiceAuthsMapper.insert(invoiceAuthProcessingEntity);

            }else {
                return Response.error(returncode, result_json.getString("returnmsg"));
            }

        }catch (Exception e){
            log.error("批量上传抵扣发票,异常：",e);
            resultMap.put("code","9999");
            resultMap.put("msg",e);
            e.printStackTrace();
        }

        log.info("========批量上传抵扣发票========结束======");
        return Response.success();
    }
    /*
     * 定时查询发票抵扣勾选处理结果
     * */
//    @Scheduled(cron = "${scheduled.cron.invoiceAuthQuery}")
    public void invoiceAuthQuery(){
        //查询状态为未查询的流水号
        List<InvoiceAuthProcessingEntity> listPcLsh = invoiceAuthsMapper.selectByPcLsh();
        if (listPcLsh != null){
            for (int i = 0; i<listPcLsh.size();i++) {
                InvoiceAuthProcessingEntity processingEntity =  listPcLsh.get(i);
                String pclsh = processingEntity.getPclsh();
                String authState = processingEntity.getAuthState();

                log.info("========查询发票抵扣勾选处理结果 ========开始======");
                JSONObject reqJson = new JSONObject();
                reqJson.put("pclsh", pclsh);
                String reqStr = reqJson.toJSONString();
                try{
                    log.info("========入参======>>>"+reqStr);
                    url = url+"203065/CXFPDKGXCLJG";
                    LqHttpUtil lqHttpUtil = new LqHttpUtil();
                    JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
                    String returncode = result_json.getString("returncode");
                    JSONArray fpmxArray = result_json.getJSONArray("fpmx");
                    if("00".equals(returncode)) {
                        if (authState.equals("01")){
                            if (fpmxArray!= null) {
                                for (Object obj : fpmxArray) {
                                    JSONObject fpmxJson = (JSONObject) obj;
                                    ElectronicledgerEntity electronicledgerEntity = new ElectronicledgerEntity();
                                    String fphm = fpmxJson.getString("fphm");
                                    String skssq = fpmxJson.getString("skssq");
                                    //处理结果  01勾选（撤销）成功，02查无此票；03该票异常无法勾选；04该票已经逾期无法认证；05当期已锁定（已申请统计）;06已勾选无法重复勾选;07未到期发票不可勾选（开票月份大于当前属期);11低版本发票;12机动车异常发票;13该票号码重复；31待处理农产品发票未确认；99其他
                                    String cljg = fpmxJson.getString("cljg");
                                    String gxsj = fpmxJson.getString("gxsj");//勾选时间 撤销勾选时此字段为空

                                    //发票状态 处理结果为03：该票异常无法勾选时  根据实际情况反馈值 0：正常 1：失控 2：作废 3：已红冲 7：部分红冲  8：全额红冲
                                    String fpzt = fpmxJson.getString("fpzt");//发票状态

                                    //是否异常凭证  处理结果为03：该票异常无法勾选时 根据实际情况反馈值 01:正常；02:异常凭证；03:疑似异常凭证
                                    String sfycpz = fpmxJson.getString("sfycpz");//是否异常凭证

                                    //锁定状态  处理结果为03：该票异常无法勾选时 根据实际情况反馈值 01:未锁定；02:已锁定
                                    String sdzt = fpmxJson.getString("sdzt");//锁定状态

                                    //当前勾选用途  处理结果为06：已勾选无法重复勾选时 根据实际情况反馈值 1:已申请抵扣；2:已申请退税；3:已申请代办退税；4:已勾选不抵扣（历史数据）；5:已申请代办退税（历史数据）;6:已申请不抵扣;11:东奥退税
                                    String hxyt = fpmxJson.getString("hxyt");//当前勾选用途

                                    //成品油异常标识  处理结果为03：该票异常无法勾选时 根据实际情况反馈值 9：正常； 1：成品油单价异常；2：成品油超库存异常；8：正常，需全额红冲
                                    String cpyycbs = fpmxJson.getString("cpyycbs");//成品油异常标识


                                    //认证状态 (0-未认证 ,1-已认证 ,2-认证失败 ,3-待认证,4-认证中)
                                    //当处理结果等于01  修改发票为已认证状态
                                    if (cljg.equals("01")){
                                        electronicledgerEntity.setAuthState("1");
                                        electronicledgerEntity.setAuthResult(cljg);
                                        if (StringUtils.isNotEmpty(skssq)){
                                            electronicledgerEntity.setAuthPeriod(skssq);
                                        }
                                        electronicledgerEntity.setAuthDate(gxsj);
                                        if (StringUtils.isNotEmpty(fpzt)){
                                            electronicledgerEntity.setInvoiceState(fpzt);
                                        }
                                    }else if (cljg.equals("03")){//03该票异常无法勾选
                                        electronicledgerEntity.setAuthState("2");
                                        electronicledgerEntity.setAuthResult(cljg);
                                        if (StringUtils.isNotEmpty(fpzt)){
                                            electronicledgerEntity.setInvoiceState(fpzt);
                                        }
                                        if (StringUtils.isNotEmpty(sfycpz)){
                                            electronicledgerEntity.setSfycpz(sfycpz);
                                        }
                                        if (StringUtils.isNotEmpty(sdzt)){
                                            electronicledgerEntity.setSdzt(sdzt);
                                        }
                                        if (StringUtils.isNotEmpty(cpyycbs)){
                                            electronicledgerEntity.setCpyycbs(cpyycbs);
                                        }
                                    }else if (cljg.equals("06")){//06已勾选无法重复勾选
                                        electronicledgerEntity.setAuthState("1");//改为已认证
                                        electronicledgerEntity.setAuthResult(cljg);
                                        if (StringUtils.isNotEmpty(fpzt)){
                                            electronicledgerEntity.setInvoiceState(fpzt);
                                        }
                                        if (StringUtils.isNotEmpty(hxyt)){
                                            electronicledgerEntity.setCpyycbs(hxyt);
                                        }
                                    }else {
                                        electronicledgerEntity.setAuthState("2");//改为认证失败
                                        electronicledgerEntity.setAuthResult(cljg);
                                        if (StringUtils.isNotEmpty(fpzt)){
                                            electronicledgerEntity.setInvoiceState(fpzt);
                                        }
                                        if (StringUtils.isNotEmpty(skssq)){
                                            electronicledgerEntity.setAuthPeriod(skssq);
                                        }
                                    }
                                    UpdateWrapper<ElectronicledgerEntity> updateWrapper = new UpdateWrapper();
                                    updateWrapper.eq("invoiceNo",fphm);
                                    baseMapper.update(electronicledgerEntity, updateWrapper);
                                }
                            }
                        }


                        InvoiceAuthProcessingEntity invoiceAuthProcessingEntity = new InvoiceAuthProcessingEntity();
                        //修改勾选处理结果表 为已查询状态
                        UpdateWrapper<InvoiceAuthProcessingEntity> updateWrapper = new UpdateWrapper();
                        invoiceAuthProcessingEntity.setState("1");
                        updateWrapper.eq("pclsh",pclsh);
                        invoiceAuthsMapper.update(invoiceAuthProcessingEntity, updateWrapper);
                    }else {
                        log.info("==============查询发票抵扣勾选处理结果返回错误信息==========="+returncode+":"+result_json.getString("returnmsg"));
                    }
                }catch (Exception e){
                    log.error("查询发票抵扣勾选处理结果,异常：",e.getMessage());
                    e.printStackTrace();
                }

            }

        }


    }

    /**
     * 企业认证申请情况
     * @param bean
     * @return
     */
    public Response<IPage<AuthApplyInfoVO>> authApplyInfo(PageRequest<AuthApplyInfoDTO> bean){
        AuthApplyInfoDTO dto = bean.getInfo();
        PageInfoRequest pageInfoRequest = bean.getPage();
        QueryWrapper queryWrapper = new QueryWrapper();
        if(StrUtil.isNotBlank(dto.getTaxNo())){
            queryWrapper.in("t.tax_number",dto.getTaxNo());
        }else{
            List<String> taxNos = commService.getTaxNumbers();
            queryWrapper.in("t.tax_number",taxNos);
        }
        if(StrUtil.isNotBlank(dto.getStatus())){
            queryWrapper.in("t.state",dto.getStatus());
        }
        IPage<AuthApplyInfoVO> result =
                periodMapper.queryAuthApplyInfos(new Page<>(pageInfoRequest.getCurrentPage(),pageInfoRequest.getPageSize()),queryWrapper);
        for (AuthApplyInfoVO vo:result.getRecords()){
            vo.setState(CodeConvertUtil.periodStatus(vo.getState()));
            vo.setApplyTaskState(CodeConvertUtil.taskStatus(vo.getApplyTaskState()));
            vo.setApplyBusinessState(CodeConvertUtil.applyBusinessStatus(vo.getApplyBusinessState()));
            vo.setSignatureTaskState(CodeConvertUtil.taskStatus(vo.getSignatureTaskState()));
            vo.setSignatureSusinessStateName(CodeConvertUtil.signatureBusinessStatus(vo.getSignatureSusinessState()));
        }
        return Response.success(result);
    }
    /**
     * 发票认证提交申请
     *
     * @param bean
     * @return
     */
    public Response authApplySubmit(ApplyDTO bean) {
        if (StrUtil.hasBlank(bean.getNsrsbh())) {
            return Response.error(ResultConstant.RET_P0003_CODE, ResultConstant.RET_P0003_MSG);
        }
        Response response = apiClientService.apply(bean);
        if (CodeConstant.T0000.equals(response.getCode())) {
            Map<String, String> resMap = JSONUtil.toBean(response.getData().toString(), Map.class);
            updateTaskNoByApply(bean.getNsrsbh(), resMap.get("taskNo"));
        } else {
            log.error("method:【authApplySubmit】接口调用失败：{}", JSONUtil.toJsonStr(response));
            return Response.error(ResultConstant.RET_P9999_CODE, ResultConstant.RET_P9999_MSG + response.getMsg());
        }
        return Response.success();
    }


    /**
     * 发票认证申请撤销
     *
     * @param bean
     * @return
     */
    public Response authApplyCancel(ApplyDTO bean) {
        if (StrUtil.hasBlank(bean.getNsrsbh())) {
            return Response.error(ResultConstant.RET_P0003_CODE, ResultConstant.RET_P0003_MSG);
        }
        Response response = apiClientService.apply(bean);
        if (CodeConstant.T0000.equals(response.getCode())) {
            Map<String, String> resMap = JSONUtil.toBean(response.getData().toString(), Map.class);
            updateTaskNoByCancel(bean.getNsrsbh(), resMap.get("taskNo"));
        } else {
            log.error("method:【authApplySubmit】接口调用失败：{}", JSONUtil.toJsonStr(response));
            return Response.error(ResultConstant.RET_P9999_CODE, ResultConstant.RET_P9999_MSG + response.getMsg());
        }
        return Response.success();
    }

    /**
     * 发票认证申请结果
     *
     * @param bean
     * @return
     */
    public Response authApplyResult(ApplyResultDTO bean) {
        if (StrUtil.hasBlank(bean.getNsrsbh())) {
            return Response.error(ResultConstant.RET_P0003_CODE, ResultConstant.RET_P0003_MSG);
        }
        Response response = apiClientService.applyResult(bean);
        if (CodeConstant.T0000.equals(response.getCode())) {
            AuthApplyContentRespVO pojo = JSONUtil.toBean(response.getData().toString(), AuthApplyContentRespVO.class);
            //更新申请结果
            if (!"1".equals(pojo.getTaskStatus())) {
                return Response.error(ResultConstant.RET_P0004_CODE, ResultConstant.RET_P0004_MSG);
            } else {
                updateApplyStatus(bean.getNsrsbh(), pojo.getTaskStatus(), pojo.getTaskResult().getBusinessStatus(), pojo.getTaskResult().getBusinessData().getStatisticsTime());
                pojo.setTaskStatusName(CodeConvertUtil.taskStatus(pojo.getTaskStatus()));
                pojo.getTaskResult().setBusinessStatusName(CodeConvertUtil.applyBusinessStatus(pojo.getTaskResult().getBusinessStatus()));
                pojo.setStatisticsTime(pojo.getTaskResult().getBusinessData().getStatisticsTime());
                return Response.success(pojo);
            }
        } else {
            log.error("method:【authApplyResult】接口调用失败：{}", JSONUtil.toJsonStr(response));
            return Response.error(ResultConstant.RET_P9999_CODE, ResultConstant.RET_P9999_MSG + response.getMsg());
        }
    }

    /**
     * 发票认证申请统计签名确认
     *
     * @param bean
     * @return
     */
    public Response authApplyConfirm(ConfirmApplyDTO bean) {
        if (StrUtil.hasBlank(bean.getNsrsbh())) {
            return Response.error(ResultConstant.RET_P0003_CODE, ResultConstant.RET_P0003_MSG);
        }
        //公司信息里增加认证抵扣确认密码
        String authPass = baseMapper.queryAuthPass(bean.getNsrsbh());
        if (StringUtil.isEmpty(authPass)) {
            return Response.error(ResultConstant.RET_P0005_CODE, ResultConstant.RET_P0005_MSG);
        }
        bean.setConfirmInfo(authPass);
        Response response = apiClientService.confirm(bean);
        if (CodeConstant.T0000.equals(response.getCode())) {
            Map<String, String> resMap = JSONUtil.toBean(response.getData().toString(), Map.class);
            updateTaskNoByConfirm(bean.getNsrsbh(), resMap.get("taskNo"));
            return Response.success();
        } else {
            log.error("method:【authApplyConfirm】接口调用失败：{}", JSONUtil.toJsonStr(response));
            return Response.error(ResultConstant.RET_P9999_CODE, ResultConstant.RET_P9999_MSG + response.getMsg());
        }
    }


    /**
     * 发票认证签名确认情况
     *
     * @param bean
     * @return
     */
    public Response authApplyConfirmResult(ConfirmApplyResultDTO bean) {
        if (StrUtil.hasBlank(bean.getNsrsbh())) {
            return Response.error(ResultConstant.RET_P0003_CODE, ResultConstant.RET_P0003_MSG);
        }
        Response response = apiClientService.confirmResult(bean);
        if (CodeConstant.T0000.equals(response.getCode())) {
            AuthApplyContentRespVO pojo = JSONUtil.toBean(response.getData().toString(), AuthApplyContentRespVO.class);
            //更新签名确认结果
            if (!"1".equals(pojo.getTaskStatus())) {
                return Response.error(ResultConstant.RET_P0004_CODE, ResultConstant.RET_P0004_MSG);
            } else {
                updateSignatureStatus(bean.getNsrsbh(), pojo.getTaskStatus(), pojo.getTaskResult().getBusinessStatus());
                pojo.setTaskStatusName(CodeConvertUtil.taskStatus(pojo.getTaskStatus()));
                pojo.getTaskResult().setBusinessStatusName(CodeConvertUtil.applyBusinessStatus(pojo.getTaskResult().getBusinessStatus()));
                return Response.success(pojo);
            }
        } else {
            log.error("method:【authApplyConfirmResult】接口调用失败：{}", JSON.toJSONString(response));
            return Response.error(ResultConstant.RET_P9999_CODE, ResultConstant.RET_P9999_MSG + response.getMsg());
        }
    }


    /**
     * 将认证申请提交后的任务号更新到业务表里
     * @param taxNo
     * @param taskNo
     */
    private void updateTaskNoByApply(String taxNo, String taskNo) {
        PeriodEntity periodEntity = new PeriodEntity();
        periodEntity.setTaskno(taskNo);
        periodEntity.setSubmitUserid(UserInfoUtil.getUserID());
        periodEntity.setSubmitTime(new Date());
        periodEntity.setState(CodeConstant.COMM_CODE_1);
        UpdateWrapper<PeriodEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("tax_number", taxNo);
        periodMapper.update(periodEntity, updateWrapper);
    }

    /**
     * 取消认证申请提交后刷新到业务表里
     * @param taxNo
     * @param taskNo
     */
    private void updateTaskNoByCancel(String taxNo, String taskNo) {
        PeriodEntity periodEntity = new PeriodEntity();
        periodEntity.setTaskno(taskNo);
        periodEntity.setCancelUserid(UserInfoUtil.getUserID());
        periodEntity.setCancelTime(new Date());
        periodEntity.setState(CodeConstant.COMM_CODE_3);
        UpdateWrapper<PeriodEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("tax_number", taxNo);
        periodMapper.update(periodEntity, updateWrapper);
    }


    /**
     * @param taxNo
     * @param applyTaskStatus
     * @param applyBusinessStatus
     * @param statisticsTime
     */
    private void updateApplyStatus(String taxNo, String applyTaskStatus, String applyBusinessStatus, String statisticsTime) {
        PeriodEntity periodEntity = new PeriodEntity();
        periodEntity.setApplyTaskState(applyTaskStatus);
        periodEntity.setApplyBusinessState(applyBusinessStatus);
        periodEntity.setStatisticsTime(statisticsTime);
        UpdateWrapper<PeriodEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("tax_number", taxNo);
        periodMapper.update(periodEntity, updateWrapper);
    }

    /**
     * @param taxNo
     * @param taskNo
     */
    private void updateTaskNoByConfirm(String taxNo, String taskNo) {
        PeriodEntity periodEntity = new PeriodEntity();
        periodEntity.setSignTaskno(taskNo);
        periodEntity.setConfirmUserid(UserInfoUtil.getUserID());
        periodEntity.setConfirmTime(new Date());
        periodEntity.setState(CodeConstant.COMM_CODE_2);
        UpdateWrapper<PeriodEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("tax_number", taxNo);
        periodMapper.update(periodEntity, updateWrapper);
    }

    /**
     * 更新签名确认结果
     *
     * @param taxNo
     * @param signatureTaskStatus
     * @param signatureBusinessStatus
     */
    private void updateSignatureStatus(String taxNo, String signatureTaskStatus, String signatureBusinessStatus) {
        PeriodEntity periodEntity = new PeriodEntity();
        periodEntity.setSignatureTaskState(signatureTaskStatus);
        periodEntity.setSignatureSusinessState(signatureBusinessStatus);
        UpdateWrapper<PeriodEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("tax_number", taxNo);
        periodMapper.update(periodEntity, updateWrapper);
    }

    /**
     * 更新发票状态待认证
     */
    private void updateInvoiceWait(List<String> uuidList) {
        ElectronicledgerEntity entity = new ElectronicledgerEntity();
        entity.setAuthState(CodeConstant.COMM_CODE_3);
        entity.setAuthUserid(UserInfoUtil.getUserID());
        entity.setAuthTime(new Date());
        UpdateWrapper<ElectronicledgerEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("invoice_id",uuidList);
        baseMapper.update(entity,updateWrapper);
    }
    private  String getStr(){
        return
                "{\n" +
                        "  \"taxNo\": \"1111111\",\n" +
                        "  \"businessType\": \"1\",\n" +
                        "  \"taskNo\": \"1111111111111\",\n" +
                        "  \"taskStatus\": \"1\",\n" +
                        "  \"taskResult\": {\n" +
                        "    \"businessStatus\": \"1\",\n" +
                        "    \"businessMsg\": \"申请统计成功\",\n" +
                        "    \"businessData\": {\n" +
                        "      \"statisticsMonth\": \"2021\",\n" +
                        "      \"statisticsTime\": \"04\",\n" +
                        "      \"normal\": [{\n" +
                        "        \"invoiceType\": \"11\",\n" +
                        "        \"deductibleNum\": \"22\",\n" +
                        "        \"deductibleAmount\": \"33\",\n" +
                        "        \"deductibleTax\": \"44\",\n" +
                        "        \"unDeductibleNum\": \"55\",\n" +
                        "        \"unDeductibleAmount\": \"66\",\n" +
                        "        \"unDeductibleTax\": \"77\"\n" +
                        "      }],\n" +
                        "      \"abnormal\": [{\n" +
                        "        \"invoiceType\": \"1\",\n" +
                        "        \"deductibleNum\": \"2\",\n" +
                        "        \"deductibleAmount\": \"3\",\n" +
                        "        \"deductibleTax\": \"4\",\n" +
                        "        \"unDeductibleNum\": \"5\",\n" +
                        "        \"unDeductibleAmount\": \"6\",\n" +
                        "        \"unDeductibleTax\": \"7\"\n" +
                        "      }]\n" +
                        "    }\n" +
                        "  }\n" +
                        "}";

    }
}
